package com.intelligent.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.intelligent.utils.Result;
import com.intelligent.dto.PurchaseOrderQueryDTO;
import com.intelligent.pojo.PurchaseOrder;
import com.intelligent.service.PurchaseOrderService;
import com.intelligent.vo.PurchaseOrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * 采购订单控制器
 */
@Slf4j
@RestController
@Api(tags = "采购订单管理")
@RequestMapping("/purchase/order")
public class PurchaseOrderController {

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    //分页
    @ApiOperation("分页查询采购订单")
    @PostMapping("/page")
    public Result<IPage<PurchaseOrderVO>> queryPage(
            @RequestBody(required = false) PurchaseOrderQueryDTO queryDTO,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        if (queryDTO == null) {
            queryDTO = new PurchaseOrderQueryDTO();
        }
        IPage<PurchaseOrderVO> page = purchaseOrderService.queryPage(queryDTO, pageNum, pageSize);
        return Result.success(page);
    }

    /**
     * 获取采购订单详情
     * @param id 采购订单ID
     * @return 采购订单详情
     */
    @ApiOperation("获取采购订单详情")
    @PostMapping("/getById")
    public Result<PurchaseOrder> getById(@RequestParam("id") Long id) {
        PurchaseOrder order = purchaseOrderService.getById(id);
        return Result.success(order);
    }

    /**
     * 新增采购订单
     * @param purchaseOrder 采购订单信息
     * @return 是否成功
     */
    @ApiOperation("新增采购订单")
    @PostMapping
    public Result<Boolean> create(@RequestBody PurchaseOrder purchaseOrder) {
        boolean success = purchaseOrderService.createPurchaseOrder(purchaseOrder);
        return success ? Result.success(true) : Result.error("新增采购订单失败");
    }

    @ApiOperation("更新采购订单")
    @PutMapping
    public Result<Boolean> update(@RequestBody PurchaseOrder purchaseOrder) {
        try {
            boolean ok = purchaseOrderService.updatePurchaseOrder(purchaseOrder);
            return ok ? Result.success(true) : Result.error("更新失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @ApiOperation("删除采购订单")
    @DeleteMapping
    public Result<Boolean> delete(@RequestBody java.util.List<Long> ids) {
        boolean ok = purchaseOrderService.deleteByIds(ids);
        return ok ? Result.success(true) : Result.error("删除失败");
    }

    @ApiOperation("导出采购订单")
    @PostMapping("/export")
    public void export(@RequestBody PurchaseOrderQueryDTO queryDTO, javax.servlet.http.HttpServletResponse response) {
        try {
            java.util.List<PurchaseOrderVO> list = purchaseOrderService.queryList(queryDTO);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"purchase-order.xlsx\"");
            java.io.PrintWriter writer = response.getWriter();
            writer.println("订单号,采购类型,供应商,数量,金额,入库状态,付款状态");
            for (PurchaseOrderVO vo : list) {
                writer.println(String.join(",",
                        safe(vo.getOrderNo()),
                        safe(vo.getPurchaseTypeName()),
                        safe(vo.getSupplierName()),
                        String.valueOf(vo.getPurchaseQuantity() == null ? 0 : vo.getPurchaseQuantity()),
                        String.valueOf(vo.getPurchaseAmount() == null ? 0 : vo.getPurchaseAmount()),
                        safe(vo.getStorageStatusName()),
                        safe(vo.getPaymentStatusName())
                ));
            }
            writer.flush();
        } catch (Exception e) {
            try {
                response.reset();
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":500,\"message\":\"导出失败\"}");
            } catch (Exception ignored) {}
        }
    }

    private String safe(String s) { return s == null ? "" : s.replace(",", " "); }


    /**
     * 生成采购订单号
     * @return 采购订单号
     */
    @ApiOperation("生成采购订单号")
    @PostMapping("/generateOrderNo")
    public Result<String> generateOrderNo() {
        String orderNo = purchaseOrderService.generateOrderNo();
        return Result.success(orderNo);
    }
}
